from django.views.generic import ListView, CreateView, UpdateView, DeleteView, View
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import get_object_or_404, redirect
from django.urls import reverse_lazy
from django.http import JsonResponse
from django.contrib import messages
from .models import Collect
from .forms import CollectForm, CollectNotesForm
from main.models import TouristAttraction


class MyCollectionsView(LoginRequiredMixin, ListView):
    """我的收藏列表"""
    model = Collect
    template_name = 'collect/my_collections.html'
    context_object_name = 'collections'
    paginate_by = 12

    def get_queryset(self):
        return Collect.objects.filter(user=self.request.user).select_related('attraction')


class AddCollectView(LoginRequiredMixin, CreateView):
    """添加收藏"""
    model = Collect
    form_class = CollectForm

    def form_valid(self, form):
        attraction_id = self.kwargs.get('attraction_id')
        attraction = get_object_or_404(TouristAttraction, id=attraction_id, status='published')

        # 检查是否已经收藏
        if Collect.objects.filter(user=self.request.user, attraction=attraction).exists():
            messages.warning(self.request, '您已经收藏过这个景点了！')
            return redirect('main:attraction_detail', pk=attraction_id)

        form.instance.user = self.request.user
        form.instance.attraction = attraction

        response = super().form_valid(form)
        messages.success(self.request, '收藏成功！')

        if self.request.headers.get('x-requested-with') == 'XMLHttpRequest':
            return JsonResponse({
                'success': True,
                'message': '收藏成功！',
                'collect_count': attraction.collects.count()
            })

        return response

    def get_success_url(self):
        return reverse_lazy('main:attraction_detail', kwargs={'pk': self.kwargs['attraction_id']})


class QuickCollectView(LoginRequiredMixin, View):
    """快速收藏（无备注）"""

    def post(self, request, attraction_id):
        attraction = get_object_or_404(TouristAttraction, id=attraction_id, status='published')

        # 检查是否已经收藏
        if Collect.objects.filter(user=request.user, attraction=attraction).exists():
            if request.headers.get('x-requested-with') == 'XMLHttpRequest':
                return JsonResponse({'success': False, 'message': '您已经收藏过这个景点了！'})
            messages.warning(request, '您已经收藏过这个景点了！')
            return redirect('main:attraction_detail', pk=attraction_id)

        # 创建收藏
        Collect.objects.create(user=request.user, attraction=attraction)

        if request.headers.get('x-requested-with') == 'XMLHttpRequest':
            return JsonResponse({
                'success': True,
                'message': '收藏成功！',
                'collect_count': attraction.collects.count()
            })

        messages.success(request, '收藏成功！')
        return redirect('main:attraction_detail', pk=attraction_id)


class UpdateCollectView(LoginRequiredMixin, UpdateView):
    """更新收藏备注"""
    model = Collect
    form_class = CollectNotesForm
    template_name = 'collect/update_collect.html'

    def get_queryset(self):
        return Collect.objects.filter(user=self.request.user)

    def form_valid(self, form):
        response = super().form_valid(form)
        messages.success(self.request, '备注更新成功！')

        if self.request.headers.get('x-requested-with') == 'XMLHttpRequest':
            return JsonResponse({'success': True, 'message': '备注更新成功！'})

        return response

    def get_success_url(self):
        return reverse_lazy('collect:my_collections')


class DeleteCollectView(LoginRequiredMixin, DeleteView):
    """删除收藏"""
    model = Collect
    template_name = 'collect/delete_collect.html'

    def get_queryset(self):
        return Collect.objects.filter(user=self.request.user)

    def delete(self, request, *args, **kwargs):
        self.object = self.get_object()
        attraction_name = self.object.attraction.name

        response = super().delete(request, *args, **kwargs)
        messages.success(request, f'已取消收藏：{attraction_name}')

        if request.headers.get('x-requested-with') == 'XMLHttpRequest':
            return JsonResponse({'success': True, 'message': '取消收藏成功！'})

        return response

    def get_success_url(self):
        return reverse_lazy('collect:my_collections')


class ToggleCollectView(LoginRequiredMixin, View):
    """切换收藏状态"""

    def post(self, request, attraction_id):
        # 确保用户已登录
        if not request.user.is_authenticated:
            return JsonResponse({
                'success': False,
                'message': '请先登录'
            }, status=401)

        attraction = get_object_or_404(TouristAttraction, id=attraction_id, status='published')

        try:
            # 检查是否已经收藏
            collect = Collect.objects.filter(user=request.user, attraction=attraction).first()

            if collect:
                # 如果已收藏，则取消收藏
                collect.delete()
                message = '取消收藏成功！'
                collected = False
            else:
                # 如果未收藏，则添加收藏
                Collect.objects.create(user=request.user, attraction=attraction)
                message = '收藏成功！'
                collected = True

            # 获取更新后的收藏数量
            collect_count = Collect.objects.filter(attraction=attraction).count()

            return JsonResponse({
                'success': True,
                'message': message,
                'collected': collected,
                'collect_count': collect_count
            })

        except Exception as e:
            return JsonResponse({
                'success': False,
                'message': f'操作失败: {str(e)}'
            }, status=500)